package com.syq.controller;


import com.syq.pojo.User;
import com.syq.service.UserService;
import com.syq.service.impl.UserServiceImpl;
import com.syq.utils.StringUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet(name = "LoginServlet", value = "/userservlet")
public class UserServlet extends BaseServlet {

    public String login(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String username = request.getParameter("username");
        String pwd = request.getParameter("pwd");
        if (StringUtils.isEmpty(username)) {
            request.setAttribute("msg", "用户名不能为空");
            return "/login.jsp";
        }
        if (StringUtils.isEmpty(pwd)) {
            request.setAttribute("msg", "密码不能为空");
            return "/login.jsp";
        }
        UserService userservice = new UserServiceImpl();

            User user = userservice.find(username, pwd);
            request.setAttribute("user",user);
            if (user!=null) {
                return "/profileservlet?method=list";
            }
            request.setAttribute("msg", "用户名密码错误");
            return "redirect:/login.jsp";
    }

    public String register(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String username = request.getParameter("username");
        String pwd = request.getParameter("pwd");
        if (StringUtils.isEmpty(username)) {
            request.setAttribute("msg", "用户名不能为空");
            return "/register.jsp";
        }
        if (StringUtils.isEmpty(pwd)) {
            request.setAttribute("msg", "密码不能为空");
            return "/register.jsp";
        }
        UserService userservice = new UserServiceImpl();
        User user=new User(0,username,pwd,1);
        try {
            userservice.add(user);
            return "/login.jsp";
        } catch (Exception e) {
            e.printStackTrace();
            return "redirect:/register.jsp";
        }
    }

    public String logout(HttpServletRequest request,HttpServletResponse response)throws Exception{
        return "redirect:/login.jsp";
    }
}
